<template>
  <div class="history-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span><el-icon><Clock /></el-icon> 处理历史</span>
          <div class="header-actions">
            <el-button @click="selectedRecords = []" v-if="selectedRecords.length > 0">
              取消选择 ({{ selectedRecords.length }})
            </el-button>
            <el-button type="success" @click="showBatchTrainingDialog" v-if="selectedRecords.length > 0 && hasUntrainedSelected">
              批量训练
            </el-button>
            <el-button type="danger" @click="batchDelete" v-if="selectedRecords.length > 0">
              批量删除
            </el-button>
            <el-button @click="loadHistory">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 优化后的筛选栏 -->
      <div class="filter-bar">
        <div class="filter-row">
          <div class="filter-group">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                size="default"
                style="width: 280px;"
                @change="handleDateChange"
            />
            <el-select v-model="statusFilter" placeholder="状态筛选" size="default" style="width: 120px;" @change="handleFilterChange">
              <el-option label="全部状态" value="" />
              <el-option label="处理中" value="processing" />
              <el-option label="已完成未训练" value="completed" />
              <el-option label="已训练" value="trained" />
              <el-option label="失败" value="failed" />
            </el-select>
          </div>
          <div class="search-group">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索文件名"
                prefix-icon="Search"
                clearable
                size="default"
                style="width: 240px;"
                @clear="handleSearch"
                @keyup.enter="handleSearch"
            />
            <el-button type="primary" size="default" @click="handleSearch">搜索</el-button>
            <el-button size="default" @click="clearAllFilters">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 历史记录网格 -->
      <div v-loading="loading" class="history-grid">
        <div
            v-for="record in historyList"
            :key="record.task_id"
            class="history-item"
            :class="{ selected: isSelected(record.task_id) }"
        >
          <div class="history-preview">
            <video
                v-if="record.result_url && record.status === 'completed'"
                :src="basePythonURL2 + record.result_url"
                :poster="basePythonURL2 + record.preview_url"
                controls
                style="width: 100%; height: 400px;"
            />
            <el-tag
                class="status-tag"
                :type="getStatusType(record.status, record.trained)"
                size="small"
            >
              <span>{{ getStatusText(record.status, record.trained) }}</span>
            </el-tag>

            <div v-if="isSelected(record.task_id)" class="selection-badge">
              <el-icon><Check /></el-icon>
            </div>
          </div>

          <div class="history-info" @click="toggleSelection(record)">
            <h4 class="task-name">{{ record.output_name || '未命名' }}</h4>
            <div class="task-files">
              <div class="file-item">
                <el-icon><User /></el-icon>
                <span>{{ record.human_name }}</span>
              </div>
              <div class="file-item">
                <el-icon><Picture /></el-icon>
                <span>{{ record.background_name }}</span>
              </div>
            </div>
            <div class="task-meta">
              <span class="create-time">{{ formatDate(record.created_time) }}</span>
              <span v-if="record.processing_time" class="process-time">
                用时: {{ formatDuration(record.processing_time) }}
              </span>
            </div>
            <div class="task-actions">
              <el-button
                  v-if="record.status === 'completed' && record.result_available"
                  type="primary"
                  size="small"
                  @click.stop="downloadResult(record)"
              >
                <el-icon><Download /></el-icon>
                下载
              </el-button>
              <!-- 添加训练按钮 -->
              <el-button
                  v-if="record.status === 'completed' && !record.trained"
                  type="success"
                  size="small"
                  @click.stop="showTrainingDialog(record)"
              >
                <el-icon><VideoPlay /></el-icon>
                去训练
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click.stop="deleteRecord(record)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 单个训练分类选择对话框 -->
      <TrainingCategoryDialog
          v-model="showCategoryDialog"
          :video-path="selectedVideoPath"
          :task-record="selectedRecord"
          @training-complete="handleTrainingComplete"
      />

      <!-- 批量训练对话框 -->
      <BatchTrainingDialog
          v-model="showBatchDialog"
          :selected-records="selectedTrainingRecords"
          @training-complete="handleBatchTrainingComplete"
      />

      <!-- 空状态 -->
      <el-empty v-if="!loading && historyList.length === 0" description="暂无处理记录" />

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 48, 96]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
<!--    <el-dialog-->
<!--        v-model="showDetailDialog"-->
<!--        :title="`任务详情 - ${detailRecord?.output_name || '未命名'}`"-->
<!--        width="800px"-->
<!--    >-->
<!--      <div v-if="detailRecord" class="detail-content">-->
<!--        <div class="detail-preview">-->

<!--          <video-->
<!--              v-if="detailRecord.result_url && detailRecord.status === 'completed'"-->
<!--              :src="basePythonURL2 + detailRecord.result_url"-->
<!--              :preload="basePythonURL2 + detailRecord.preview_url"-->
<!--              controls-->
<!--              style="width: 100%; max-height: 400px;"-->
<!--          />-->
<!--          <el-empty v-else description="无预览" />-->
<!--        </div>-->

<!--        <el-descriptions :column="2" border style="margin-top: 20px;">-->
<!--          <el-descriptions-item label="任务ID">-->
<!--            {{ detailRecord.task_id }}-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item label="状态">-->
<!--            <el-tag :type="getStatusType(detailRecord.status, detailRecord.trained)">-->
<!--              {{ getStatusText(detailRecord.status, detailRecord.trained) }}-->
<!--            </el-tag>-->
<!--          </el-descriptions-item>-->
<!--          &lt;!&ndash; 添加训练状态显示 &ndash;&gt;-->
<!--          <el-descriptions-item label="训练状态" v-if="detailRecord.status === 'completed'">-->
<!--            <el-tag :type="detailRecord.trained ? 'success' : 'info'">-->
<!--              {{ detailRecord.trained ? '已训练' : '未训练' }}-->
<!--            </el-tag>-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item label="数字人文件">-->
<!--            {{ detailRecord.human_name }}-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item label="背景文件">-->
<!--            {{ detailRecord.background_name }}-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item label="创建时间">-->
<!--            {{ formatDate(detailRecord.created_time) }}-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item label="完成时间">-->
<!--            {{ detailRecord.completed_time ? formatDate(detailRecord.completed_time) : '-' }}-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item label="处理时长" :span="2">-->
<!--            {{ detailRecord.processing_time ? formatDuration(detailRecord.processing_time) : '-' }}-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item label="参数设置" :span="2">-->
<!--            <pre>{{ JSON.stringify(detailRecord.parameters, null, 2) }}</pre>-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item v-if="detailRecord.error_message" label="错误信息" :span="2">-->
<!--            <el-alert type="error" :closable="false">-->
<!--              {{ detailRecord.error_message }}-->
<!--            </el-alert>-->
<!--          </el-descriptions-item>-->
<!--        </el-descriptions>-->
<!--      </div>-->

<!--      <template #footer>-->
<!--        <el-button @click="showDetailDialog = false">关闭</el-button>-->
<!--        <el-button-->
<!--            v-if="detailRecord?.status === 'completed' && detailRecord?.result_available"-->
<!--            type="primary"-->
<!--            @click="downloadResult(detailRecord)"-->
<!--        >-->
<!--          下载结果-->
<!--        </el-button>-->
<!--      </template>-->
<!--    </el-dialog>-->
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api, { basePythonURL2 } from '@/api'
import TrainingCategoryDialog from '@/components/TrainingCategoryDialog.vue'
import BatchTrainingDialog from '@/components/BatchTrainingDialog.vue'
import {View} from "@element-plus/icons-vue";

// 响应式数据
const showCategoryDialog = ref(false)
const showBatchDialog = ref(false)
const selectedVideoPath = ref('')
const selectedRecord = ref(null)
const loading = ref(false)
const historyList = ref([])
const selectedRecords = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const searchKeyword = ref('')
const statusFilter = ref('')
const dateRange = ref(null)
const showDetailDialog = ref(false)
const detailRecord = ref(null)
let searchTimer = null

// 计算属性
const hasUntrainedSelected = computed(() => {
  return selectedRecords.value.some(taskId => {
    const record = historyList.value.find(r => r.task_id === taskId)
    return record && record.status === 'completed' && !record.trained
  })
})

const selectedTrainingRecords = computed(() => {
  return historyList.value.filter(record =>
      selectedRecords.value.includes(record.task_id) &&
      record.status === 'completed' &&
      !record.trained
  )
})

// 方法
const loadHistory = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchKeyword.value,
      status: statusFilter.value,
      startDate: dateRange.value ? dateRange.value[0] : '',
      endDate: dateRange.value ? dateRange.value[1] : ''
    }

    const result = await api.getHistory(params)
    historyList.value = result.items || []
    total.value = result.total || 0
  } catch (error) {
    ElMessage.error('加载历史记录失败')
  } finally {
    loading.value = false
  }
}

const handleDateChange = () => {
  currentPage.value = 1
  loadHistory()
}

const handleFilterChange = () => {
  currentPage.value = 1
  loadHistory()
}

const handleSearch = () => {
  currentPage.value = 1
  loadHistory()
}

const debouncedSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 300)
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadHistory()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadHistory()
}

const isSelected = (taskId) => {
  return selectedRecords.value.includes(taskId)
}

const toggleSelection = (record) => {
  const taskId = record.task_id
  const index = selectedRecords.value.indexOf(taskId)
  if (index > -1) {
    selectedRecords.value.splice(index, 1)
  } else {
    selectedRecords.value.push(taskId)
  }
}

const deleteRecord = async (record) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除这条处理记录吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await api.deleteHistory(record.task_id)
    ElMessage.success('删除成功')
    loadHistory()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const batchDelete = async () => {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRecords.value.length} 条记录吗？`,
        '批量删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    for (const taskId of selectedRecords.value) {
      await api.deleteHistory(taskId)
    }

    ElMessage.success('批量删除成功')
    selectedRecords.value = []
    loadHistory()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const downloadResult = (record) => {
  if (record.result_url) {
    api.downloadFile(record.result_url.split('/').pop())
  } else {
    ElMessage.warning('下载链接不存在')
  }
}

const showDetail = (record) => {
  detailRecord.value = record
  showDetailDialog.value = true
}

const getStatusType = (status, trained) => {
  if (status === 'completed') {
    return trained ? 'primary' : 'success'
  }

  const typeMap = {
    'pending': 'info',
    'processing': 'warning',
    'failed': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status, trained) => {
  if (status === 'completed') {
    return trained ? '已训练' : '已合成未训练'
  }

  const textMap = {
    'pending': '等待中',
    'processing': '处理中',
    'failed': '失败'
  }
  return textMap[status] || status
}

const showTrainingDialog = (record) => {
  selectedRecord.value = record
  selectedVideoPath.value = record.result_path || ''
  showCategoryDialog.value = true
}

const showBatchTrainingDialog = () => {
  if (selectedTrainingRecords.value.length === 0) {
    ElMessage.warning('请选择未训练的已完成记录')
    return
  }
  showBatchDialog.value = true
}

const handleTrainingComplete = async (result) => {
  if (result.success) {
    ElMessage.success('训练任务已提交')
    // 刷新列表
    await loadHistory()
  } else {
    ElMessage.error('训练失败：' + (result.message || '未知错误'))
  }
}

const handleBatchTrainingComplete = async (result) => {
  if (result.success) {
    ElMessage.success(`批量训练完成: 成功${result.successCount}个，失败${result.failedCount}个`)
    selectedRecords.value = []
    await loadHistory()
    showBatchDialog.value = false
  } else {
    ElMessage.error('批量训练失败：' + (result.message || '未知错误'))
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return dateStr
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    return dateStr
  }
}

const clearAllFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  dateRange.value = null
  currentPage.value = 1
  loadHistory()
}

const formatDuration = (seconds) => {
  if (!seconds) return '-'
  if (seconds < 60) return `${seconds}秒`
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分${seconds % 60}秒`
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}小时${minutes}分`
}

// 生命周期
onMounted(() => {
  loadHistory()
})
</script>

<style lang="scss" scoped>
.task-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;

  .el-button {
    &.el-button--small {
      padding: 5px 10px;

      .el-icon {
        margin-right: 4px;
      }
    }
  }
}

/* 更新状态标签样式 */
.status-tag {
  &.el-tag--success {
    /* 已完成未训练的样式 */
    &:not(.trained) {
      background-color: #e6a23c;
      border-color: #e6a23c;
      color: #fff;
    }
  }
}

.history-page {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 20px;
    font-weight: 600;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

/* 优化后的筛选栏样式 */
.filter-bar {
  margin-bottom: 20px;

  .filter-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;

    .filter-group {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .search-group {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .filter-bar .filter-row {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;

    .filter-group,
    .search-group {
      justify-content: center;
      flex-wrap: wrap;
    }
  }
}

@media (max-width: 768px) {
  .filter-bar .filter-row {
    .filter-group,
    .search-group {
      flex-direction: column;
      align-items: stretch;

      .el-date-picker,
      .el-select,
      .el-input {
        width: 100% !important;
      }
    }
  }
}

.filter-info {
  margin-bottom: 15px;
}

.history-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  min-height: 300px;
}

.history-item {
  position: relative;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  background: white;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-color: #c0c4cc;
  }

  &.selected {
    border-color: #409eff;
    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
  }
}

.history-preview {
  position: relative;
  width: 100%;
  background: #f5f7fa;
  cursor: pointer;

  .el-image {
    width: 100%;
    height: 100%;

    ::v-deep(.el-image__inner){
      width: auto;
      height: 100% !important;
      display: block !important;
      margin: auto !important;
    }
  }

  .preview-error,
  .preview-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #c0c4cc;
    gap: 8px;

    .el-icon {
      font-size: 48px;
    }
  }

  .status-tag {
    position: absolute;
    top: 10px;
    left: 10px;
  }

  .selection-badge {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 28px;
    height: 28px;
    background: #409eff;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.history-info {
  padding: 15px;

  .task-name {
    margin: 0 0 10px 0;
    font-size: 16px;
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .task-files {
    margin-bottom: 10px;

    .file-item {
      display: flex;
      align-items: center;
      gap: 5px;
      margin-bottom: 5px;
      font-size: 14px;
      color: #606266;

      span {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .task-meta {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 12px;
    color: #909399;
  }

  .task-actions {
    display: flex;
    gap: 8px;
  }
}

.pagination-wrapper {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.detail-content {
  .detail-preview {
    text-align: center;
    margin-bottom: 20px;
    background: #f5f7fa;
    padding: 20px;
    border-radius: 8px;
    width: 100%;

    .el-image {
      height: 100%;

      ::v-deep(.el-image__inner){
        width: auto;
        height: 100% !important;
        display: block !important;
        margin: auto !important;
      }
    }
  }

  pre {
    background: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    font-size: 12px;
    overflow-x: auto;
  }
}
</style>